package com.yuebanmaoshare.file.service.impl;

import com.yuebanmaoshare.file.domain.Favorite;
import com.yuebanmaoshare.file.domain.UserFile;
import com.yuebanmaoshare.file.mapper.FavoriteMapper;
import com.yuebanmaoshare.file.service.FavoriteService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class FavoriteServiceImpl implements FavoriteService {
    
    @Resource
    private FavoriteMapper favoriteMapper;

    @Override
    public List<Favorite> getFavoriteList(String userId) {
        List<Favorite> favoriteList = favoriteMapper.selectFavoriteList(userId);
        // 处理userFile可能为null的情况，避免序列化时报错
        if (favoriteList != null) {
            for (Favorite favorite : favoriteList) {
                if (favorite.getUserFile() == null) {
                    // 如果userFile为null，可以创建一个空的UserFile对象或者跳过
                    // 这里我们创建一个空的UserFile对象并设置isDir等字段的默认值
                    UserFile userFile = new UserFile();
                    userFile.setIsDir(0); // 默认设置为文件
                    // 可以根据需要设置其他默认字段
                    favorite.setUserFile(userFile);
                } else {
                    // 如果userFile不为null，确保isDir字段不为null
                    if (favorite.getUserFile().getIsDir() == null) {
                         favorite.getUserFile().setIsDir(0); // 设置默认值
                    }
                }
            }
        }
        return favoriteList;
    }

    @Override
    public boolean addFavorite(String userId, String fileId) {
        Favorite favorite = new Favorite();
        favorite.setFavoriteId(UUID.randomUUID().toString().replace("-", ""));
        favorite.setUserId(userId);
        favorite.setFileId(fileId);
        favorite.setCreateTime(new Date());
        favorite.setModifyTime(new Date());
        return favoriteMapper.insertFavorite(favorite) > 0;
    }

    @Override
    public boolean removeFavorite(String userId, String fileId) {
        return favoriteMapper.deleteFavorite(userId, fileId) > 0;
    }

    @Override
    public boolean isFavorite(String userId, String fileId) {
        return favoriteMapper.selectFavoriteByFileId(userId, fileId) != null;
    }
} 